<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="商铺编号" prop="shopId">
        <el-input v-model="queryParams.shopId" placeholder="请输入商铺编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户姓名" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入客户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="预存款状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择预存款状态" clearable @change="handleQuery">
          <el-option v-for="dict in dict.type.sys_prepay_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:pay:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate"
          v-hasPermi="['system:pay:edit']">退还</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payList">
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="商铺编号" align="center" prop="shopId" />
      <el-table-column label="客户姓名" align="center" prop="clientName" />
      <el-table-column label="预存款状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_prepay_type" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="收费项目" align="center" prop="itemName" :formatter="formatItemName" />
      <el-table-column label="付款方式" align="center" prop="payWay">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_pay_type" :value="scope.row.payWay" />
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="收款人" align="center" prop="payee" />
      <el-table-column label="收款时间" align="center" prop="paytime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paytime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单号" align="center" prop="id" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            v-hasPermi="['system:pay:edit']" v-show="true" :disabled="scope.row.status !== 0">打印收款单</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" v-hasPermi="['system:pay:remove']"
            v-show="true" :disabled="scope.row.status === 0">打印退款单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加预存款管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商铺编号" prop="shopsId">
          <el-input v-model="shopsId" placeholder="请输入商铺编号" class="shop" />
          <el-button type="primary" @click="getShopsList">搜 索</el-button>
        </el-form-item>
        <el-form-item label="客户姓名" prop="clientName">
          <el-input :value="shops?shops.userName:''" placeholder="请输入客户姓名" :disabled="true" />
        </el-form-item>
        <el-form-item label="可用收费项" prop="selectcan">
          <el-radio-group v-model="form.selectcan">
            <el-radio v-for="dict in dict.type.sys_canpay_type" :key="dict.value" :label="parseInt(dict.value)"
              @change.native="selectedradio(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收费项目" prop="itemName" v-show="selected">
          <el-select v-model="form.freeItemId" placeholder="请选择收费项目" @change="handleSelectChange">
            <el-option v-for="item in feeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式" prop="payWay">
          <el-select v-model="form.payWay" placeholder="请选择付款方式">
            <el-option v-for="dict in dict.type.sys_pay_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="收款时间" prop="paytime">
          <el-date-picker v-model="form.paytime" type="datetime" placeholder="选择收款时间" format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 退还预存款管理对话框 -->
    <el-dialog :title="title" :visible.sync="editflag" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商铺编号" prop="shopsId">
          <el-input v-model="shopsId" placeholder="请输入商铺编号" class="shop" />
          <el-button type="primary" @click="getShopsList">搜 索</el-button>
        </el-form-item>
        <el-form-item label="客户姓名" prop="clientName">
          <el-input :value="shops?shops.userName:''" placeholder="请输入客户姓名" :disabled="true" />
        </el-form-item>
        <el-form-item label="退还方式" prop="payWay">
          <el-select v-model="form.payWay" placeholder="请选择退还方式">
            <el-option v-for="dict in dict.type.sys_pay_type" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="退还时间" prop="paytime">
          <el-date-picker v-model="form.paytime" type="datetime" placeholder="请选择退还时间" format="yyyy-MM-dd"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="editList">
        <el-table-column type="index" label="序号" />
        <el-table-column label="收费项" align="center" prop="itemName" :formatter="formatItemName" />
        <el-table-column label="账户金额" align="center" prop="amount" />
        <el-table-column label="退还金额" align="center" prop="amount">
          <template slot-scope="scope">
            <el-input v-model="scope.row.amount" type="number" :default-value="0"
              @input="handleInputChange(scope.row, scope.$index, $event)"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPay,
    getPay,
    delPay,
    addPay,
    updatePay
  } from "@/api/system/pay";
  import {
    listFee_item
  } from "@/api/system/fee_item";
  import {
    listContract
  } from "@/api/system/contract";

  export default {
    name: "Pay",
    dicts: ['sys_canpay_type', 'sys_prepay_type', 'sys_pay_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 预存款管理表格数据
        payList: [],
        // 退还表格数据
        editList: [],
        // 收费项数据
        feeList: [],
        // 商铺id
        shopsId: null,
        // 商铺数据
        shops: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示退还对话框
        editflag: false,
        // 指定收费项后显示收费项目
        selected: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          shopId: null,
          clientName: null,
          status: null,
        },
        // 表单参数
        form: {
          freeItemId: null,
        },
        edit: {},
        // 表单校验
        rules: {
          shopId: [{
            required: true,
            message: "商铺Id不能为空",
            trigger: "blur"
          }],
          clientName: [{
            required: true,
            message: "客户姓名不能为空",
            trigger: "blur"
          }],
          selectcan: [{
            required: true,
            message: "可用收费项不能为空",
            trigger: "change"
          }],
          payWay: [{
            required: true,
            message: "付款方式不能为空",
            trigger: "blur"
          }],
          amount: [{
            required: true,
            message: "金额不能为空",
            trigger: "blur"
          }],
          freeItemId: [{
            required: true,
            message: "收费项目不能为空",
            trigger: "blur"
          }],
          paytime: [{
            required: true,
            message: '请选择收款时间',
            trigger: 'change'
          }, ],
        }
      };
    },
    created() {
      this.getList();
      this.getFeeList();
    },
    methods: {
      /** 查询预存款管理列表 */
      getList() {
        this.loading = true;
        listPay(this.queryParams).then(response => {
          this.payList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询收费项数据 */
      getFeeList() {
        listFee_item({
          pageNum: 1,
          pageSize: 9999,
        }).then(resp => {
          this.feeList = resp.rows;
        })
      },
      /** 查询商铺信息 */
      getShopsList() {
        listContract({
          resourceId: this.shopsId
        }).then(resp => {
          console.log(resp);
          this.shops = resp.rows[0];
          this.form.shopId = resp.rows[0].resourceId;
          this.form.clientId = resp.rows[0].ownerId;
          this.form.clientName = resp.rows[0].userName;
          this.form.status = 0;
        })
        if (this.title === '退还') {
          listPay({
            shopId: this.shopsId
          }).then(resp => {
            this.editList = resp.rows;
            console.log(this.editList);
            this.form = this.editList[0];
            this.form.status = 1;
          });
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.editflag = false;
        this.selected = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          shopId: null,
          clientId: null,
          clientName: null,
          status: null,
          selectcan: null,
          freeItemId: null,
          itemName: null,
          payWay: null,
          amount: null,
          payee: null,
          paytime: null
        };
        this.shopsId = null;
        this.shops = null;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 收费项目改变 */
      handleSelectChange(selectedId) {
        console.log(this.feeList);
        // 遍历 feeList 来找到 selectedId 对应的 name
        const selectedItem = this.feeList.find(item => item.id === selectedId);
        if (selectedItem) {
          // 如果找到了对应的项目，更新 form.itemName 为其 name
          this.form.itemName = selectedItem.name;
        } else {
          // 如果没有找到，可以设置一个默认值或者清空 form.itemName
          this.form.itemName = '';
        }
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 单选框值改变 */
      selectedradio(index) {
        if (index == 1) {
          this.selected = true;
          this.form.freeItemId = null;
        } else {
          this.selected = false;
          this.form.freeItemId = 0;
        }
      },
      /** 收费项目未指定 */
      formatItemName(row, column, cellValue) {
        if (!cellValue) {
          return '不指定收费项';
        }
        return cellValue;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增";
      },
      /** 退还按钮操作 */
      handleUpdate() {
        this.reset();
        this.title = "退还";
        this.editflag = true;
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            addPay(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        });
      },
    }
  };
</script>
<style scoped>
  .shop {
    width: 200px;
  }
</style>
